//
//  HBPageSegmentViewController.m
//  HBLibary
//
//  Created by Rambo on 2018/8/20.
//

#import "HBPageSegmentViewController.h"
//#import "HBPageSegmentView.h"

@interface HBPageSegmentViewController ()<UIScrollViewDelegate>
{
    CGFloat _screenWidth;
}

@property (nonatomic, strong) HBPageSegmentView *pageSegmentView;

@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, strong) NSArray *titles;

@property (nonatomic, assign) NSInteger defaultSelectIndex;

@property (nonatomic, strong) UIFont *titleFont;

@property (nonatomic, weak) NSLayoutConstraint *pageSegmentViewLayoutConstraint;

@property (nonatomic, assign) CGFloat minMargin;

@property (nonatomic, assign) CGFloat tagWidth;
@end


@implementation HBPageSegmentViewController

/**
 快速创建 HBPageSegmentViewController
 
 @param titleFont 分段标题字体大小
 @param titles 分段标题数组
 @param viewControllers 控制器数组
 @param minMargin 分段标题之间最小间隙
 @param selectIndex 默认选中
 @return HBPageSegmentViewController 实例
 */
- (instancetype)initWithPageSegmentTitleFont:(UIFont*)titleFont titles:(NSArray <NSString *>*)titles viewControllers:(NSArray <UIViewController *> *)viewControllers minMargin:(CGFloat)minMargin defaultSelectIndex:(NSInteger)selectIndex{
    return [self initWithPageSegmentTitleFont:titleFont titles:titles viewControllers:viewControllers minMargin:minMargin tagWidth:0 defaultSelectIndex:selectIndex];
}

/**
 快速创建 HBPageSegmentViewController
 
 @param titleFont 分段标题字体大小
 @param titles 分段标题数组
 @param viewControllers 控制器数组
 @param minMargin 分段标题之间最小间隙
 @param tagWidth 标签宽度
 @param selectIndex 默认选中
 @return HBPageSegmentViewController 实例
 */
- (instancetype)initWithPageSegmentTitleFont:(UIFont*)titleFont titles:(NSArray <NSString *>*)titles viewControllers:(NSArray <UIViewController *> *)viewControllers minMargin:(CGFloat)minMargin tagWidth:(CGFloat)tagWidth defaultSelectIndex:(NSInteger)selectIndex{
    if (self = [super init]) {
        _tagWidth = tagWidth;
        _screenWidth = [UIScreen mainScreen].bounds.size.width;
        if (selectIndex < 0) {
            selectIndex = 0;
        }
        
        if (minMargin < 0) {
            minMargin = 0;
        }
        
        self.minMargin = minMargin;
        
        self.titleFont = titleFont;
        _pageSegmentViewHeight = 42;
        
        if (titles == nil || viewControllers == nil || ![titles isKindOfClass:[NSArray class]] || ![viewControllers isKindOfClass:[NSArray class]]) {
            @throw [NSException exceptionWithName:@"HBPageSegmentViewController" reason:@"param error" userInfo:nil];
            
        }else{
            
            if (titles.count != viewControllers.count) {
                @throw [NSException exceptionWithName:@"HBPageSegmentViewController" reason:@"Titles count unequal to viewController count" userInfo:nil];
            }
            
            NSMutableArray *titlesM = [NSMutableArray array];
            //            NSMutableArray *viewControllersM = [NSMutableArray array];
            
            NSInteger minCount = MIN(titles.count, viewControllers.count);
            
            for (NSInteger index = 0; index < minCount; index++) {
                NSString *title = titles[index];
                if (title && [title isKindOfClass:[NSString class]]) {
                    [titlesM addObject:title];
                }
                
                UIViewController *vc = viewControllers[index];
                if (vc && [vc isKindOfClass:[UIViewController class]]) {
                    //                    [viewControllersM addObject:vc];
                    [self addChildViewController:vc];
                }
            }
            
            if (titlesM.count != self.childViewControllers.count) {
                @throw [NSException exceptionWithName:@"HBPageSegmentViewController" reason:@"Titles count unequal to viewController count" userInfo:nil];
            }
            
            self.titles = titlesM.copy;
            if (self.titles.count > 0 && selectIndex >= self.titles.count) {
                selectIndex = self.titles.count - 1;
            }
            self.defaultSelectIndex = selectIndex;
            //            self.viewControllers = viewControllers;
        }
        
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
//    self.automaticallyAdjustsScrollViewInsets = NO;

    
    self.navigationController.navigationBar.translucent = NO;
    
    if ([self respondsToSelector:@selector(setAutomaticallyAdjustsScrollViewInsets:)]) {
        [self setAutomaticallyAdjustsScrollViewInsets:NO];
    }
    
    if (@available(iOS 11.0, *)){
        [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
    }
    
    [self hb_pageSegmentSetUI];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    NSArray *gestureArray = self.navigationController.view.gestureRecognizers;
    
    for (UIGestureRecognizer *gestureRecognizer in gestureArray) {
        
        if ([gestureRecognizer isKindOfClass:[UIScreenEdgePanGestureRecognizer class]]) {
            
            [self.scrollView.panGestureRecognizer requireGestureRecognizerToFail:gestureRecognizer];
            
        }
        
    }
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    NSInteger index = scrollView.contentOffset.x / scrollView.frame.size.width;
    [self.pageSegmentView selectPageWithIndex:index];
    [self loadChildControllerViewWithIndex:index];
}

#pragma mark - 私有方法

- (void)loadChildControllerViewWithIndex:(NSInteger)index{
    if (self.childViewControllers.count <= index) return;
    UIViewController *vc = self.childViewControllers[index];
    if ([self.scrollView.subviews containsObject:vc.view]) return;
    [self.scrollView addSubview:vc.view];
    vc.view.frame = CGRectMake(index * _screenWidth, 0, _screenWidth, self.scrollView.frame.size.height);
    
}


#pragma mark - 初始化

- (void)hb_pageSegmentSetUI{
    
    if (self.titles == nil || self.titles.count == 0) return;
    
    UIView *superView = self.view;
    
    [superView addSubview:self.pageSegmentView];
    NSLayoutConstraint *layoutConstraintLeft = [NSLayoutConstraint constraintWithItem:self.pageSegmentView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:superView attribute:NSLayoutAttributeLeft multiplier:1 constant:0];
    [superView addConstraint:layoutConstraintLeft];
    
    NSLayoutConstraint *layoutConstraintRight = [NSLayoutConstraint constraintWithItem:self.pageSegmentView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:superView attribute:NSLayoutAttributeRight multiplier:1 constant:0];
    [superView addConstraint:layoutConstraintRight];
    
    NSLayoutConstraint *layoutConstraintTop = [NSLayoutConstraint constraintWithItem:self.pageSegmentView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:superView attribute:NSLayoutAttributeTop multiplier:1 constant:0];
    [superView addConstraint:layoutConstraintTop];
    
    NSLayoutConstraint *layoutConstraintHeight = [NSLayoutConstraint constraintWithItem:self.pageSegmentView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeHeight multiplier:1 constant:_pageSegmentViewHeight];
    [superView addConstraint:layoutConstraintHeight];
    _pageSegmentViewLayoutConstraint = layoutConstraintHeight;

    
    self.scrollView = ({
        UIScrollView *scrollView = [[UIScrollView alloc] init];
        scrollView.delegate = self;
        scrollView.contentSize = CGSizeMake(self.titles.count * _screenWidth, 0);
        scrollView.pagingEnabled = YES;
        scrollView.bounces = NO;
        scrollView.showsHorizontalScrollIndicator = NO;
        [superView addSubview:scrollView];
        
        scrollView.translatesAutoresizingMaskIntoConstraints = NO;
        
        NSArray *layoutConstraints_H = [NSLayoutConstraint constraintsWithVisualFormat:@"|[scrollView]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(scrollView)];
        [self.view addConstraints:layoutConstraints_H];;
        
        NSLayoutConstraint *layoutConstraintTop = [NSLayoutConstraint constraintWithItem:scrollView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.pageSegmentView attribute:NSLayoutAttributeBottom multiplier:1 constant:0];
        [superView addConstraint:layoutConstraintTop];
        
        NSLayoutConstraint *layoutContraintBottom = [NSLayoutConstraint constraintWithItem:scrollView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:superView attribute:NSLayoutAttributeBottom multiplier:1 constant:0];
        [superView addConstraint:layoutContraintBottom];
        
        scrollView;
    });
    
    [self.view layoutIfNeeded];
    
    
    if (self.childViewControllers.count > self.defaultSelectIndex) {
        [self.pageSegmentView selectPageWithIndex:self.defaultSelectIndex];
        [self.scrollView setContentOffset:CGPointMake(self.defaultSelectIndex*_screenWidth, 0) animated:YES];
        [self loadChildControllerViewWithIndex:self.defaultSelectIndex];
    }
    
}

#pragma mark - set

- (void)setPageSegmentViewHeight:(CGFloat)pageSegmentViewHeight{
    if (pageSegmentViewHeight < 0) {
        pageSegmentViewHeight = 0;
    }
    _pageSegmentViewHeight = pageSegmentViewHeight;
    
    if (self.pageSegmentViewLayoutConstraint == nil) return;
    
    self.pageSegmentViewLayoutConstraint.constant = _pageSegmentViewHeight;
    
    [self.view setNeedsLayout];
    [self.view layoutIfNeeded];
}

#pragma mark - 懒加载

- (HBPageSegmentView *)pageSegmentView{
    if (!_pageSegmentView) {
        __weak typeof(self) weakSelf = self;
        _pageSegmentView = [[HBPageSegmentView alloc] initWithTitles:self.titles titleFont:self.titleFont minMargin:self.minMargin tagWidth:_tagWidth complete:^(NSInteger currentPage)  {
            
            __strong typeof(weakSelf) strongSelf = weakSelf;
            if (!strongSelf) return;
            [strongSelf loadChildControllerViewWithIndex:currentPage];
            if (strongSelf.scrollView.contentOffset.x == strongSelf->_screenWidth * currentPage) return;
            [strongSelf.scrollView setContentOffset:CGPointMake(strongSelf->_screenWidth * currentPage, 0) animated:YES];
        }];
        _pageSegmentView.translatesAutoresizingMaskIntoConstraints = NO;
    }
    return _pageSegmentView;
}

@end
